<?php

namespace app\common\model\ad;

use app\common\utils\Utils;
use think\Model;


class Ads extends Model
{

    

    

    // 表名
    protected $name = 'self_ad_ads';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'target_text',
        'expiretime_text',
        'effectime_text',
        'src_text',
        'time_tag_text'
    ];


    public function getTimeTagTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');

        return Utils::get_last_time($value);
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
        Ads::beforeUpdate(function ($ad) {
            $before = Ads::get($ad['id']);
            if ($before['switch'] == 0 && $ad['switch'] == 1) {
                $ad->createtime = time();
            }
        });
    }

    
    public function getTargetList()
    {
        return ['_self' => __('_self'), '_blank' => __('_blank')];
    }


    public function getTargetTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['target']) ? $data['target'] : '');
        $list = $this->getTargetList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getSrcTextAttr($value, $data) {
        $value = $value ? $value : (isset($data['src']) ? $data['src'] : '');
        return cdnurl($value, true);
    }

    public function getExpiretimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['expiretime']) ? $data['expiretime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEffectimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['effectime']) ? $data['effectime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setExpiretimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEffectimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function getShowTypeTextAttr($value, $data) {
        $value = $value ? $value : (isset($data['show_type']) ? $data['show_type'] : '');

        $list = $this->getShowTypeList();

        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getShowTypeList()
    {
        return ['0' => '上中下(上文字.中图片.下文字)', '1' => '上左右(上文字.左图片.右文字)', '2' => '上下(上文字.下文字)'];
    }



}
